package com.atguigu.gmall.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.app.BaseAppV1;
import com.atguigu.gmall.common.Constant;
import com.atguigu.gmall.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.PatternTimeoutFunction;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/31 10:35
 */
public class DwmJumpDetailApp_1 extends BaseAppV1 {
    public static void main(String[] args) {
        new DwmJumpDetailApp_1().init(3002, 1, "DwmJumpDetailApp_1", "DwmJumpDetailApp_1", Constant.TOPIC_DWD_PAGE);
    }
    
    @Override
    protected void run(StreamExecutionEnvironment env, DataStreamSource<String> sourceStream) {
        /*sourceStream =
            env.fromElements(
                "{\"common\":{\"mid\":\"101\"},\"page\":{\"page_id\":\"home\"},\"ts\":10000} ",
                "{\"common\":{\"mid\":\"101\"},\"page\":{\"page_id\":\"home\"},\"ts\":11000} ",
                "{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"home\"},\"ts\":10000}",
                "{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"good_list\",\"last_page_id\":" +
                    "\"home\"},\"ts\":17000} ",
                "{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"good_list\",\"last_page_id\":" +
                    "\"detail\"},\"ts\":50000} "
            );*/
        
        
    
    
    
        // 1. 有个流
        KeyedStream<JSONObject, String> stream = sourceStream
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((log, ts) -> log.getLong("ts"))
            )
            .keyBy(obj -> obj.getJSONObject("common").getString("mid"));
        // 2. 定义模式: 开始是入口, 然后紧跟着一个页面  正常
        // 跳出:
        Pattern<JSONObject, JSONObject> pattern = Pattern
            .<JSONObject>begin("entry")
            .where(new SimpleCondition<JSONObject>() {
                @Override
                // 入口的条件
                public boolean filter(JSONObject value) throws Exception {
                    String lastPageId = value.getJSONObject("page").getString("last_page_id");
                    return lastPageId == null || lastPageId.isEmpty();
                }
            })
            .next("nextPage")
            .where(new SimpleCondition<JSONObject>() {
                @Override
                // 入口的条件
                public boolean filter(JSONObject value) throws Exception {
                    String lastPageId = value.getJSONObject("page").getString("last_page_id");
                    return lastPageId == null || lastPageId.isEmpty();
                }
            })
            
            .within(Time.seconds(5));
    
        // 3. 把模式应用到流上
        PatternStream<JSONObject> ps = CEP.pattern(stream, pattern);
    
        // 4. 取出满足模式数据(或者超时数据)
        SingleOutputStreamOperator<JSONObject> normal = ps.select(
            new OutputTag<JSONObject>("timeout") {},
            new PatternTimeoutFunction<JSONObject, JSONObject>() {
                @Override
                public JSONObject timeout(Map<String, List<JSONObject>> pattern,
                                          long timeoutTimestamp) throws Exception {
                    // 超时数据, 就是跳出明细
                    return pattern.get("entry").get(0);
                }
            },
            new PatternSelectFunction<JSONObject, JSONObject>() {
                @Override
                public JSONObject select(Map<String, List<JSONObject>> pattern) throws Exception {
                    return pattern.get("entry").get(0); // 满足正常访问的数据, 不用返回
                }
            }
        );
        normal
            .union(normal.getSideOutput(new OutputTag<JSONObject>("timeout") {}))
            .map(JSONAware::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWM_USER_JUMP_DETAIL));
        
    }
}
/*
dwd_start dwd_page dwd_display
uv
1. 使用 dwd_start 数据
        理论上可以的.

        当用浏览器直接访问的时候, 是没有启动日志

2. 使用 dwd_page
        保存下来今天的第一次页面日志

------

一个用户跳出有什么特质
    1. 当前页面应该是入口
        上一个页面是空
    2. 过了一段时间, 没有再访问其他页面
        超时时间

找到满足上面两个条件的page日志明细

CEP

------
模式:

第一个是入口, 第二个也是入口


入口1 入口2 入口3 进入其他页面  入口4
 */